import { InjectLabelKey } from "@/views/domain/kubeHud/api/k8s/defination";
import type {
  Container,
  Deployment
} from "@/views/domain/kubeHud/api/k8s/types";
import { newDeployment } from "@/views/domain/kubeHud/api/k8s/usage";
import { ref } from "vue";

const podAffinityOption = (appName?: string) => ({
  podAffinity: {
    preferredDuringSchedulingIgnoredDuringExecution: [
      {
        weight: 100,
        podAffinityTerm: {
          topologyKey: InjectLabelKey.Hostname,
          labelSelector: {
            matchLabels: {
              app: appName
            }
          }
        }
      }
    ]
  }
});

const podAntiAffinityOption = (appName?: string) => ({
  podAntiAffinity: {
    preferredDuringSchedulingIgnoredDuringExecution: [
      {
        weight: 100,
        podAffinityTerm: {
          topologyKey: InjectLabelKey.Hostname,
          labelSelector: {
            matchLabels: {
              app: appName
            }
          }
        }
      }
    ]
  }
});

export class EditContext {
  // 编辑对象
  editDeployment = ref<Deployment>({});

  constructor(val?: Deployment) {
    this.editDeployment.value = val ?? newDeployment();
  }

  newContainerTpl(): Container {
    return {};
  }

  // 更新负载名称
  updateDeploymentName = (name: string) => {
    this.editDeployment.value.metadata.name = name;
    this.editDeployment.value.metadata.labels.app = name;
  };

  // 设置默认的亲和性-集中调度
  setDefaultPodAffinity() {
    this.editDeployment.value.spec.template.spec.affinity = podAffinityOption(
      this.editDeployment.value.metadata.labels.app
    );
  }

  // 设置默认的亲和性-分散调度
  setDefaultPodAntiAffinity() {
    this.editDeployment.value.spec.template.spec.affinity =
      podAntiAffinityOption(this.editDeployment.value.metadata.labels.app);
  }
}

// 当前编辑上下文
let currentContext: EditContext = undefined;

// 创建工作负载弹窗显示
const dialogVisible = ref(false);

// 打开编辑器
const openDeploymentEditor = (val?: Deployment) => {
  currentContext = new EditContext(val);
  dialogVisible.value = true;
};

// 关闭编辑器
const closeDeploymentEditor = () => {
  currentContext = undefined;
  dialogVisible.value = false;
};

export const useDeploymentEditor = () => {
  return {
    openDeploymentEditor,
    closeDeploymentEditor,
    dialogVisible,
    editDeployment: currentContext?.editDeployment,
    updateDeploymentName: currentContext?.updateDeploymentName,
    editContext: currentContext,
    podAffinityOption,
    podAntiAffinityOption
  };
};
